package com.strongbj.iot.devices.guis.request.handle;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.guis.message.GUISOSMessageFactory;
import com.strongbj.iot.devices.guis.message.MQMessageOfGUIS;
import com.strongbj.iot.devices.guis.request.entity.SetTheMainframeTheIncomeEntity;
import com.strongbj.iot.devices.guis.respnose.common.RedirectOutputStream;
import com.strongbj.iot.devices.guis.respnose.handle.GUISResponseHandleContext;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

/**
 * 上位机设置主机网络信息  Handel
 * @author 25969
 *
 */
public class SetHostNetworkInformationHandle implements IMessageHandle<MQMessageOfGUIS,Object>{
	private static Logger logger = LogManager.getLogger(SetHostNetworkInformationHandle.class.getName());
	private final static String ACTION_CODE = "reader025";   //MQ中判断消息类型的标识符
	private final static byte command = (byte)0x06;
	private GUISOSMessageFactory gUISOSMessageFactory = new GUISOSMessageFactory();
//	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static SimpleDateFormat df=null;
	@Override
	public boolean isHandle(MQMessageOfGUIS t) {
		if(t.getActioncode().equals(ACTION_CODE)){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfGUIS t) {
		logger.info("GUIS 收到MQ发来的“上位机设置主机网络信息” json={}",JSON.toJSONString(t));
		SetTheMainframeTheIncomeEntity setTheMainframeTheIncome = ((JSONObject)t.getAwsPostdata()).toJavaObject(SetTheMainframeTheIncomeEntity.class);
		 this.messageDataToBytes(setTheMainframeTheIncome);
		return null;
	}

	/**
	 * 解析并下发数据给下位机
	 * @param setTheMainframeTheIncome
	 */
	private void messageDataToBytes(SetTheMainframeTheIncomeEntity setTheMainframeTheIncome) {
	    String nativeIPAddress = setTheMainframeTheIncome.getNativeIPAddress();   //本机IP地址
	    String subnetMask = setTheMainframeTheIncome.getSubnetMask();            //子网掩码
		String gateway = setTheMainframeTheIncome.getGateway();                  //网关
		String dns = setTheMainframeTheIncome.getDns();                          //DNS
//		int localPort = setTheMainframeTheIncome.getLocalPort();              //本机端口
		String targetIaddressIp = setTheMainframeTheIncome.getTargetIaddressIp();//目标IP
		int targetPort = setTheMainframeTheIncome.getTargetPort();            //目标端口
		byte[] lightComByte = new byte[22];   //装数据的byte数组
	    //4byte(本机IP地址)+4byte(掩码)+4byte(网关)+4byte(dns)+2byte(本机端口号)+4byte（目标IP地址）+2byte（目标端口号）
		byte [] pTmp=ByteUtil.ipToBytesByInet(nativeIPAddress);
		System.arraycopy(pTmp, 0, lightComByte, 0, pTmp.length);
		       pTmp=ByteUtil.ipToBytesByInet(subnetMask);
		System.arraycopy(pTmp, 0, lightComByte, 4, pTmp.length);
	           pTmp=ByteUtil.ipToBytesByInet(gateway);
		System.arraycopy(pTmp, 0, lightComByte, 8, pTmp.length);
		       pTmp=ByteUtil.ipToBytesByInet(dns);
	    System.arraycopy(pTmp, 0, lightComByte, 12, pTmp.length);
	           pTmp=ByteUtil.ipToBytesByInet(targetIaddressIp);
	    System.arraycopy(pTmp, 0, lightComByte, 16, pTmp.length);
	    ByteUtil.shortToBytes((short)targetPort, lightComByte,20);
	    
		byte[] dest = new byte[3];   //接受主机编号的临时byte数组		
		byte[] datas = gUISOSMessageFactory.createGUISOSMessage(ByteUtil.hexStringToBytes(setTheMainframeTheIncome.getDevAddrCode(),dest,0), command, lightComByte);
	    
		ByteBuf bs  = Unpooled.copiedBuffer(datas);
		GUISResponseHandleContext.channels.writeAndFlush(bs);
		logger.info("GUIS 发送上位机设置主机网络信息命令成功 message={}",ByteUtil.byteArrToHexString(datas));
		 df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		RedirectOutputStream.put(df.format(new Date())+"上位机 发送 设置主机网络信息命令成功 message={}    "+ByteUtil.byteArrToHexString(datas));
	}
	
	public static void main(String[] args) {
		byte[] lightComByte = new byte[2];   //装数据的byte数组
//	String b ="00000000000A".toLowerCase();
		
		ByteUtil.shortToBytes((short)16868, lightComByte,0);
//		int targetPort = ByteUtil.byteArrToShort(lightComByte, 0);//目标端口号
//		//int b = (int)targetPort;
//		int a=0;
	}
	
}
